﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerBody : MonoBehaviour
{
    public const string NOT_SET_STRING_VALUE = "NOT_SET";
    internal readonly int killNum;
    internal readonly Vector2 myPos;
    internal readonly Vector2 enemyPos;

    public int score
    {
        get
        {
            var tg = 0;
            for (int index = 0; index < m_monsters.Count; index++)
            {
                tg += m_monsters[index].score;
            }
            return tg;
        }
    }
    public string userId { get { return m_userId; } }
    public string headPortraitUrl { get { return m_headPortraitUrl; } }
    public string nickName { get { return m_nickName; } }

    private int m_spriteIndex = 0;
    private List<Monster> m_monsters;
    private Vector2 m_curDirection = Vector2.zero;

    private string m_userId = NOT_SET_STRING_VALUE;
    private string m_nickName = NOT_SET_STRING_VALUE;
    private string m_headPortraitUrl = NOT_SET_STRING_VALUE;

    private void OnEnable()
    {
        if (m_monsters == null)
            m_monsters = new List<Monster>();

        var initMonster = MonsterPorcessor.instance.CreateMonster(m_userId, m_spriteIndex);
        initMonster.SetScore(2000);
        initMonster.SplitEvent += m_SplitHandle;
        m_monsters.Add(initMonster);
    }



    private void Update()
    {
        foreach (var c in m_monsters)
        {
            c.SetDirection(m_curDirection);
        }
    }

    public void Init(string pUserId, string pNickName, string pHeadPortraitUrl, int pSpriteIndex)
    {
        m_userId = pUserId;
        m_nickName = pNickName;
        m_headPortraitUrl = pHeadPortraitUrl;
        m_spriteIndex = pSpriteIndex;
    }
    public void Login()
    {
        for (int index = 0; index < m_monsters.Count; index++)
        {
            m_monsters[index].isOnline = false;
        }
    }
    public void Logout()
    {
        for (int index = 0; index < m_monsters.Count; index++)
        {
            m_monsters[index].isOnline = true;
        }
    }

    public void SetMoveDirection(Vector2 pDirection)
    {
        m_curDirection = pDirection;
    }

    public void SetBisection()
    {
        var dics = new Dictionary<Monster, Monster[]>();
        foreach (var m in m_monsters)
        {
            dics.Add(m, m.Split());
        }
        foreach (var kv in dics)
        {
            m_SplitHandle(kv.Key, kv.Value);
        }
    }

    public void Stop()
    {

    }

    private void m_SplitHandle(Monster pOrigon, Monster[] pTargets)
    {
        if (pTargets == null)
            return;
        var index = m_monsters.IndexOf(pOrigon);
        m_monsters.RemoveAt(index);
        Destroy(pOrigon.gameObject);

        foreach (var m in pTargets)
        {
            m_monsters.Add(m);
            m.SplitEvent += m_SplitHandle;
        }
        Debug.LogWarning(m_monsters.Count);
    }

}
